<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>deepMerge-merge</title>
  </head>
  <body>
    <script>
      function forEach(obj, fn) {
        // Don't bother if no value provided
        if (obj === null || typeof obj === "undefined") {
          return;
        }

        // Force an array if not already something iterable
        if (typeof obj !== "object") {
          /*eslint no-param-reassign:0*/
          obj = [obj];
        }

        if (Array.isArray(obj)) {
          // Iterate over array values
          for (var i = 0, l = obj.length; i < l; i++) {
            fn.call(null, obj[i], i, obj);
          }
        } else {
          // Iterate over object keys
          for (var key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
              fn.call(null, obj[key], key, obj);
            }
          }
        }
      }

      function merge(/* obj1, obj2, obj3, ... */) {
        var result = {};
        function assignValue(val, key) {
          if (typeof result[key] === "object" && typeof val === "object") {
            result[key] = merge(result[key], val);
          } else {
            result[key] = val;
          }
        }

        for (var i = 0, l = arguments.length; i < l; i++) {
          forEach(arguments[i], assignValue);
        }
        return result;
      }

      function deepMerge(/* obj1, obj2, obj3, ... */) {
        var result = {};
        function assignValue(val, key) {
          // 当result[key]的值也是一个对象，并且遍历的对象上这个值也是object，就深拷贝
          console.log(typeof val);
          if (typeof result[key] === "object" && typeof val === "object") {
            result[key] = deepMerge(result[key], val);

            // 和merge的唯一区别是：
            // 不保留对原始对象的引用
            // 当遍历对象上的值为一个对象时，也进行深拷贝到一个空对象
            // 也就是说
            // obj1 = {a:11}
            // obj2 = {person: {}}
            // 合并两个对象时，如果person是一个对象，就会用一个空的对象来装它
            // deepMerge({}, val);
          } else if (typeof val === "object") {
            console.log("--------------------");
            console.log("result", result);
            console.log("var", val);
            result[key] = deepMerge({}, val);
          } else {
            console.log(3);
            result[key] = val;
          }
        }

        for (var i = 0, l = arguments.length; i < l; i++) {
          forEach(arguments[i], assignValue);
        }
        return result;
      }

      let target = {
        name: "tony",
      };

      let o1 = { add: target };
      let o2 = {
        a: 12,
      };
      // let result = merge(o1, o2);
      // console.log(result);

      let result2 = deepMerge(o1, o2);
      console.log(result2.add === target);
    </script>
  </body>
</html>
